package com.codebase.zookeeper.zk;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.junit.Test;

import java.util.concurrent.CountDownLatch;

/**
 * zk连接  需要监听zk连接成功的事件通知
 */
public class CreateConnect implements Watcher{

    private static CountDownLatch countDownLatch = new CountDownLatch(1);

    @Override
    public void process(WatchedEvent watchedEvent) {
        System.out.println("收到消息"+ watchedEvent);

        if(Event.KeeperState.SyncConnected == watchedEvent.getState()){
            countDownLatch.countDown();
        }
    }

    /**
     * 基本会话的创建
     * @throws Exception
     */
    @Test
    public void test() throws Exception{
        ZooKeeper zooKeeper = new ZooKeeper("127.0.0.1:2181", 5000, new CreateConnect());
        System.out.println("连接等待中。。。");
        countDownLatch.await();
        System.out.println("连接成功");
    }

    /**
     * 使用用户名密码复用会话
     * @throws Exception
     */
    @Test
    public void test1() throws Exception{
        ZooKeeper zooKeeper = new ZooKeeper("127.0.0.1:2181", 5000, new CreateConnect());
        System.out.println("连接等待中。。。");
        countDownLatch.await();
        System.out.println("创建结束");


        long sessionId = zooKeeper.getSessionId();
        byte[] pass = zooKeeper.getSessionPasswd();

        System.out.println("创建开始");
        ZooKeeper zooKeeper1 = new ZooKeeper("127.0.0.1:2181", 5000, new CreateConnect(), sessionId, pass);

        Thread.sleep(300);

    }


}
